package icantalk.voip;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * Class used to create a tunnel using UDP hole punching
 * method.
 *
 * @author Antonín Brettšnajdr
 */


public class UDPTunneler {
	
	int lport,rport;
	String ip;
	DatagramSocket socket;
	
	public UDPTunneler(int localPort, String hostIP, int remotePort) throws SocketException {
		lport = localPort;
		rport = remotePort;
		ip = hostIP;
		
		socket = new DatagramSocket(localPort);
	}
	
	public void createTunnel() throws IOException {
		UDPSender sender = new UDPSender(socket,ip,rport,"CONN",1000);
		
		while(true) {
			
			DatagramPacket p = new DatagramPacket(new byte[10], 10);
			socket.receive(p);
			
			//analyse
			String data = new String(p.getData());
			if (data.indexOf("CONN") != -1) {
				sender.send("CONN");
				sender.terminate();
				break;
			}
			
		}
	}

}
